// pages/chat-detail/chat-detail.ts
import { MerchantAPI } from '../../utils/api'

interface MessageSession {
  sessionId: string;
  msgType: string;
  userInfo?: {
    userId: string;
    userName: string;
    phoneSuffix: string;
    avatar: string;
    isOnline?: boolean;
  };
  senderInfo?: {
    senderId: string;
    senderName: string;
    avatar: string;
  };
  lastMessage: {
    content: string;
    sentAt: string;
    isRead: boolean;
    senderType: string;
    messageId?: string;
  };
  unreadCount: number;
}

interface ChatMessage {
  messageId: string;
  senderType: string;
  senderId: string;
  content: string;
  messageType: string;
  sentAt: string;
  isRead: boolean;
  couponInfo?: {
    couponId: string;
    title: string;
    amount: number;
    minOrderAmount: number;
    expireAt: string;
  };
}

const DEFAULT_AVATAR = '/images/default-avatar.png';

interface ChatDetailPageData {
  loading: boolean;
  refreshing: boolean;
  sessionInfo: MessageSession | null;
  chatMessages: ChatMessage[];
  messageInput: string;
  canSendMessage: boolean;
  quickReplies: string[];
  scrollTop: number;
  scrollIntoView: string;
  showCouponModal: boolean;
  availableCoupons: any[];
  selectedCoupon: any;
  customMessage: string;
  pageNum: number;
  pageSize: number;
  hasMore: boolean;
  userAvatar: string;
  merchantAvatar: string;
}

Page({
  data: {
    loading: false,
    refreshing: false,
    sessionInfo: null,
    chatMessages: [],
    messageInput: '',
    canSendMessage: false,
    quickReplies: [],
    scrollTop: 0,
    scrollIntoView: '',
    showCouponModal: false,
    availableCoupons: [],
    selectedCoupon: null,
    customMessage: '',
    pageNum: 1,
    pageSize: 20,
    hasMore: true,
    userAvatar: DEFAULT_AVATAR,
    merchantAvatar: DEFAULT_AVATAR
  } as ChatDetailPageData,

  onLoad(options: any) {
    const sessionId = options.sessionId ? String(options.sessionId) : null;
    const sessionInfoStr = options.sessionInfo;
    
    if (!sessionId) {
      wx.showToast({
        title: '会话ID不存在',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }

    // 解析会话信息
    let sessionInfo: MessageSession | null = null;
    if (sessionInfoStr) {
      try {
        sessionInfo = JSON.parse(decodeURIComponent(sessionInfoStr));
      } catch (e) {
        console.error('解析会话信息失败:', e);
      }
    }

    const fallbackSession: MessageSession = {
      sessionId: sessionId,
      msgType: 'customer',
      userInfo: {
        userId: '0',
        userName: '用户',
        phoneSuffix: '',
        avatar: DEFAULT_AVATAR,
        isOnline: false
      },
      lastMessage: {
        content: '',
        sentAt: '',
        isRead: false,
        senderType: 'user'
      },
      unreadCount: 0
    };

    const resolvedSession = sessionInfo || fallbackSession;

    this.setData({
      sessionInfo: resolvedSession,
      userAvatar: this.getUserAvatar(resolvedSession)
    });

    this.loadMerchantAvatar();

    // 设置快捷回复
    this.setData({
      quickReplies: [
        "用餐愉快",
        "订单处理中", 
        "抱歉不便",
        "配送进度",
        "联系我"
      ]
    });

    // 加载聊天记录
    this.loadChatHistory(true);
  },

  /**
   * 从session中提取用户头像
   */
  getUserAvatar(session?: MessageSession | null): string {
    if (!session || !session.userInfo) {
      return DEFAULT_AVATAR;
    }
    const avatar = session.userInfo.avatar;
    return avatar && typeof avatar === 'string' && avatar.trim().length > 0
      ? avatar
      : DEFAULT_AVATAR;
  },

  /**
   * 提取商家头像
   */
  extractMerchantAvatar(info: any): string {
    if (!info) return '';
    return (
      info.avatarUrl ||
      info.shopAvatar ||
      info.avatar ||
      info.shopAvatarUrl ||
      info.logoUrl ||
      ''
    );
  },

  /**
   * 加载商家头像
   */
  async loadMerchantAvatar() {
    try {
      const cachedInfo = wx.getStorageSync('merchantUserInfo');
      const cachedAvatar = this.extractMerchantAvatar(cachedInfo);
      if (cachedAvatar) {
        this.setData({ merchantAvatar: cachedAvatar });
      }

      const response = await MerchantAPI.getMerchantInfo();
      if (response.code === 200 && response.data) {
        const remoteAvatar = this.extractMerchantAvatar(response.data);
        if (remoteAvatar) {
          this.setData({ merchantAvatar: remoteAvatar });
        }

        // 同步最新信息到本地缓存
        const mergedInfo = {
          ...(cachedInfo || {}),
          ...response.data,
          avatarUrl: remoteAvatar || response.data.avatarUrl || cachedAvatar || '',
          shopAvatar: remoteAvatar || response.data.shopAvatar || cachedAvatar || ''
        };
        wx.setStorageSync('merchantUserInfo', mergedInfo);
      }
    } catch (error) {
      console.error('加载商家头像失败:', error);
    }
  },

  /**
   * 加载聊天记录
   */
  async loadChatHistory(reset: boolean = false) {
    const sessionInfo = this.data.sessionInfo;
    if (!sessionInfo) return;

    if (reset) {
      this.setData({
        pageNum: 1,
        chatMessages: [],
        hasMore: true
      });
    }

    if (this.data.loading || (!reset && !this.data.hasMore)) {
      return;
    }

    this.setData({ loading: true });

    try {
        const response = await MerchantAPI.getSessionHistory(sessionInfo.sessionId, {
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize
      });

      if (response.code === 200) {
        const formatDateTime = (value: any) => {
          if (!value) {
            return '';
          }
          if (typeof value === 'string') {
            // 部分接口返回 ISO 字符串，统一转换为本地时间
            const parsed = Date.parse(value);
            if (!Number.isNaN(parsed)) {
              return new Date(parsed).toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
              }).replace(/\//g, '-');
            }
            return value;
          }
          if (typeof value === 'number') {
            return new Date(value).toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
              hour12: false
            }).replace(/\//g, '-');
          }
          try {
            return new Date(value).toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              second: '2-digit',
              hour12: false
            }).replace(/\//g, '-');
          } catch (error) {
            return String(value);
          }
        };

        const newMessages: ChatMessage[] = (response.rows || []).map((msg: any) => {
          const normalizedMessageId = msg.messageId != null ? String(msg.messageId) : `${Date.now()}_${Math.random().toString(36).slice(2)}`;
          const normalizedSenderId = msg.senderId != null ? String(msg.senderId) : '';
          const normalizedSenderType = typeof msg.senderType === 'string' ? msg.senderType : String(msg.senderType || '');
          const normalizedMessageType = typeof msg.messageType === 'string' ? msg.messageType : 'text';

          const couponInfo = msg.couponInfo ? {
            ...msg.couponInfo,
            couponId: msg.couponInfo.couponId != null ? String(msg.couponInfo.couponId) : '',
            expireAt: formatDateTime(msg.couponInfo.expireAt)
          } : undefined;

          const groupInfo = msg.groupInfo ? {
            ...msg.groupInfo,
            groupId: msg.groupInfo.groupId != null ? String(msg.groupInfo.groupId) : ''
          } : undefined;

          return {
            ...msg,
            messageId: normalizedMessageId,
            senderId: normalizedSenderId,
            senderType: normalizedSenderType,
            messageType: normalizedMessageType,
            content: msg.content || '',
            sentAt: formatDateTime(msg.sentAt),
            couponInfo,
            groupInfo
          };
        });

        const allMessages = reset ? newMessages : [...this.data.chatMessages, ...newMessages];
        const total = response.total || 0;

        this.setData({
          chatMessages: allMessages,
          hasMore: allMessages.length < total,
          pageNum: this.data.pageNum + 1
        });

        const unreadIds = allMessages
          .filter(msg => !msg.isRead)
          .map(msg => msg.messageId)
          .filter(id => !!id);

        if (unreadIds.length > 0) {
          this.markAsRead(unreadIds);
        }

        // 滚动到底部
        if (reset) {
          setTimeout(() => {
            this.scrollToBottom();
          }, 100);
        }
      }
    } catch (error: any) {
      console.error('加载聊天记录失败:', error);
      wx.showToast({
        title: error?.msg || '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ 
        loading: false,
        refreshing: false 
      });
    }
  },

  /**
   * 跳转到门店管理页面
   */
  goToStoreManage() {
    wx.navigateTo({
      url: '/pages/store/store'
    });
  },

  /**
   * 查看用户订单详情
   */
  viewUserOrder() {
    const sessionInfo = this.data.sessionInfo;
    if (!sessionInfo) {
      wx.showToast({
        title: '会话信息不存在',
        icon: 'none'
      });
      return;
    }

    wx.navigateTo({
      url: `/pages/order-detail/order-detail?sessionId=${sessionInfo.sessionId}`
    });
  },

  /**
   * 下拉刷新
   */
  onRefresh() {
    this.setData({ refreshing: true });
    this.loadChatHistory(true);
  },

  /**
   * 标记为已读
   */
  async markAsRead(messageIds?: string[]) {
    const sessionInfo = this.data.sessionInfo;
    if (!sessionInfo) return;
    const ids = Array.isArray(messageIds) ? messageIds.filter(id => !!id) : [];
    if (ids.length === 0) return;

    try {
      await MerchantAPI.markMessagesRead(sessionInfo.sessionId, ids);
      
      // 更新本地消息状态
      const updatedMessages = this.data.chatMessages.map(msg => {
        if (ids.includes(msg.messageId)) {
          return { ...msg, isRead: true };
        }
        return msg;
      });
      this.setData({ chatMessages: updatedMessages });
    } catch (error) {
      console.error('标记已读失败:', error);
    }
  },

  /**
   * 发送消息
   */
  async sendMessage() {
    const { sessionInfo, messageInput } = this.data;
    
    if (!messageInput.trim()) {
      return;
    }

    if (!sessionInfo) {
      wx.showToast({
        title: '会话不存在',
        icon: 'none'
      });
      return;
    }

    const messageContent = messageInput.trim();
    
    // 清空输入框
    this.setData({
      messageInput: '',
      canSendMessage: false
    });

    try {
      const response = await MerchantAPI.sendMessage(sessionInfo.sessionId, {
        content: messageContent,
        messageType: 'text'
      });

      if (response.code === 200) {
        // 发送成功，重新加载聊天记录
        await this.loadChatHistory(true);
        
        wx.showToast({
          title: '发送成功',
          icon: 'success',
          duration: 1500
        });
      } else {
        // 发送失败，恢复输入框内容
        this.setData({
          messageInput: messageContent,
          canSendMessage: messageContent.trim().length > 0
        });
        
        wx.showToast({
          title: response.msg || '发送失败，请重试',
          icon: 'none'
        });
      }
    } catch (error: any) {
      console.error('发送消息失败:', error);
      
      // 发送失败，恢复输入框内容
      this.setData({
        messageInput: messageContent,
        canSendMessage: messageContent.trim().length > 0
      });
      
      wx.showToast({
        title: error?.msg || '发送失败，请重试',
        icon: 'none'
      });
    }
  },

  /**
   * 选择快捷回复
   */
  selectQuickReply(e: any) {
    const content = e.currentTarget.dataset.content;
    this.setData({
      messageInput: content,
      canSendMessage: content.trim().length > 0
    });
  },

  /**
   * 显示优惠券列表
   */
  async showCouponModal() {
    wx.showLoading({ title: '加载中...' });

    try {
      const response = await MerchantAPI.getAvailableCoupons();

      let coupons = [];

      if (response.code === 200 && response.data && response.data.length > 0) {
        coupons = response.data;
      } else {
        coupons = [];
      }

      this.setData({
        showCouponModal: true,
        availableCoupons: coupons,
        customMessage: '为您送上专属优惠券'
      });

      wx.hideLoading();
    } catch (error) {
      console.error('加载优惠券列表失败:', error);
      wx.hideLoading();
      
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  /**
   * 选择优惠券
   */
  selectCoupon(e: any) {
    const coupon = e.currentTarget.dataset.coupon;
    this.setData({
      selectedCoupon: coupon
    });
  },

  /**
   * 发送优惠券
   */
  async sendCoupon() {
    const { sessionInfo, selectedCoupon, customMessage } = this.data;
    
    if (!selectedCoupon) {
      wx.showToast({
        title: '请选择优惠券',
        icon: 'none'
      });
      return;
    }

    if (!sessionInfo) {
      wx.showToast({
        title: '会话不存在',
        icon: 'none'
      });
      return;
    }

    this.setData({ loading: true });

    try {
      const response = await MerchantAPI.sendCoupon(sessionInfo.sessionId, {
        couponTemplateId: selectedCoupon.couponTemplateId,
        customMessage: customMessage || '为您送上专属优惠券'
      });

      if (response.code === 200) {
        // 发送成功，重新加载聊天记录
        await this.loadChatHistory(true);

        this.setData({
          showCouponModal: false,
          selectedCoupon: null,
          customMessage: ''
        });

        wx.showToast({
          title: '优惠券发送成功',
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: response.msg || '发送失败，请重试',
          icon: 'none'
        });
      }
    } catch (error: any) {
      console.error('发送优惠券失败:', error);
      wx.showToast({
        title: error?.msg || '发送失败，请重试',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  /**
   * 滚动到底部
   */
  scrollToBottom() {
    if (this.data.chatMessages.length > 0) {
      const lastMessage = this.data.chatMessages[this.data.chatMessages.length - 1];
      this.setData({
        scrollIntoView: 'msg-' + lastMessage.messageId
      });
    }
  },

  // 表单输入处理
  onMessageInput(e: any) {
    const value = e.detail.value || '';
    this.setData({
      messageInput: value,
      canSendMessage: value.trim().length > 0
    });
  },

  onCustomMessageInput(e: any) {
    this.setData({
      customMessage: e.detail.value
    });
  },

  // 弹窗控制
  closeCouponModal() {
    this.setData({
      showCouponModal: false,
      selectedCoupon: null,
      customMessage: ''
    });
  },

  preventClose() {
    // 阻止事件冒泡
  }
});

